#include <iostream>
#include <vector>
#include <string>
#include <sys/select.h>
#include "easysock.hpp"

namespace server
{

class select_server : public inet::tcp::server
{
public:
    select_server(int port) : server(port), _fds(20, -1)
    {}

    ~select_server() {}

    void start()
    {
        _fds[_sock] = _sock;

        while (true)
        {
            int maxfd = -1;
            fd_set rfds;

            for (auto fd : _fds)
            {
                if (fd == -1) continue;

                FD_SET(fd, &rfds);
                maxfd = std::max(maxfd, fd);
            }

            int n = select(maxfd + 1, &rfds, nullptr, nullptr, nullptr);

            if (n > 0)
            {
                for (auto fd : _fds)
                {
                    if (fd == -1) continue;

                    if (FD_ISSET(fd, &rfds))
                    {
                        if (fd == _sock)
                        {
                            int sock = accept();
                            _fds[sock] = sock;

                            if (sock >= 20) close(sock);
                        }
                        else 
                        {
                            std::string buf;
                            recv(fd, &buf, 1024);
                            send(fd, "server return >>> " + buf);
                        }
                    }
                }
            }
        }
    }

private:
    std::vector<int> _fds;

};

}
